
const PORT = 8000;
const { Pool } = require('pg');
const pool = new Pool({
    user: 'postgres',
    host: 'project_data_base',
    //host: '127.0.0.1',
    database: 'postgres',
    password: '1234',
    port: 5432,
  });
class populationGrowth {
     /**
     * @swagger
     * components:
     *   schemas:
     *     PopulationGrowth:
     *       type: object
     *       properties:
     *         id:
     *           type: integer
     *         number_of_individuals:
     *           type: integer
     *         mass_of_individuals:
     *           type: number
     *           format: float
     *         id_population:
     *           type: integer
     *         date_time:
     *           type: string
     *           format: date-time
     * 
     * /population_growth:
     *   get:
     *     tags: [Популяции]
     *     summary: Получение списка роста популяции
     *     parameters:
     *       - in: query
     *         name: limit
     *         schema:
     *           type: integer
     *         description: Лимит записей для возврата
     *       - in: query
     *         name: offset
     *         schema:
     *           type: integer
     *         description: Смещение для пагинации
     *       - in: query
     *         name: population
     *         schema:
     *           type: integer
     *         description: Идентификатор популяции для фильтрации
     *     responses:
     *       200:
     *         description: Список роста популяции
     *         content:
     *           application/json:
     *             schema:
     *               type: object
     *               properties:
     *                 populationGrowth:
     *                   type: array
     *                   items:
     *                     $ref: '#/components/schemas/PopulationGrowth'
     *                 next:
     *                   type: string
     *                   nullable: true
     *                 previous:
     *                   type: string
     *                   nullable: true
     *       500:
     *         description: Внутренняя ошибка сервера
     */
    async populationGrowthGet (req, res) {
          try {
            const limit = req.query.limit || 10;
            const offset = req.query.offset || 0;
            const population = req.query.population || null
            const last = req.query.last || null
            const values = [];
            
        
            var queryText = `
              SELECT * FROM populations_growth as pg full join population as p on pg.id_population = p.pid join equipment as e on p.equipment_id=e.eid
              where 1=1
            `;
            if (population !== null) {
              queryText += `AND p.pid = $1`;
              values.push(population)
            }
            if (last !== null) {
              queryText += ` order by date_time desc limit 1`;
            }
        
            var result = await pool.query(queryText, values);
            const populationGrowth = result.rows;
            if(!populationGrowth.length && last && population){
              queryText = `
              SELECT * FROM population as p join equipment as e on p.equipment_id=e.eid
              where p.pid = ${population}
            `;
            result = await pool.query(queryText);
            const response = result.rows;
            res.json(response);
            }
            else{
              const nextOffset =  populationGrowth.length < limit ? 0 : parseInt(offset) + parseInt(limit);
              const previousOffset = parseInt(offset) - parseInt(limit) >= 0 ? parseInt(offset) - parseInt(limit) : null;
          
              const response = {
                  populationGrowth,
                  next: nextOffset === 0 ? null : `http://localhost:${PORT}/population_growth?limit=${limit}&offset=${nextOffset}`,
                  previous: previousOffset === null? null : `http://localhost:${PORT}/population_growth?limit=${limit}&offset=${previousOffset}`,
              };
          
              res.json(response);
            }
          } catch (error) {
            res.status(500).json({ error: error.message });
          }
        }
        
     /**
     * @swagger
     * /population_growth:
     *   post:
     *     tags: [Популяции]
     *     summary: Создание новой записи о росте популяции
     *     requestBody:
     *       required: true
     *       content:
     *         application/json:
     *           schema:
     *             type: object
     *             properties:
     *               number_of_individuals:
     *                 type: integer
     *               mass_of_individuals:
     *                 type: number
     *                 format: float
     *               id_population:
     *                 type: integer
     *               date_time:
     *                 type: string
     *                 format: date-time
     *     responses:
     *       200:
     *         description: Новая запись о росте популяции создана
     *         content:
     *           application/json:
     *             schema:
     *               $ref: '#/components/schemas/PopulationGrowth'
     *       500:
     *         description: Внутренняя ошибка сервера
     */   
     async populationGrowthPost(req, res) {
      try {
        const { number_of_individuals, mass_of_individuals, id_population, date_time, average_mass, average_size, mortality } = req.body;
    
        const queryText = `
          INSERT INTO populations_growth (number_of_individuals, mass_of_individuals, id_population, date_time, average_mass, average_size, mortality)
          VALUES ($1, $2, $3, $4, $5, $6, $7)
          RETURNING *;
        `;
        const values = [number_of_individuals, mass_of_individuals, id_population, date_time, average_mass, average_size, mortality];
    
        const result = await pool.query(queryText, values);
        const newPopulationGrowth = result.rows[0];
    
        res.json(newPopulationGrowth);
      } catch (error) {
        res.status(500).json({ error: error.message });
      }
    }
    
}

module.exports = new populationGrowth()
